<template>
  <div class="container">
    <div class="mb10">
      <el-text class="mx-1"> 查询条件：</el-text>
    </div>
    <el-row :gutter="10">
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-select v-model.trim="searchCondition.category_id" placeholder="商品分类" clearable>
          <el-option v-for="item in categoryList" :label="item.name" :value="item.id" :key="item.id"></el-option>
        </el-select>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-input v-model.trim="searchCondition.name" placeholder="商品名称" clearable></el-input>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-select v-model.trim="searchCondition.on_sale" placeholder="是否上架" clearable>
          <el-option v-for="item in whetherStatue" :label="item.dictLabel" :value="item.dictValue" :key="item.id"></el-option>
        </el-select>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-space wrap>
          <el-button type="success" :icon="Search" :disabled="disabledbtn" @click="searchInfo">搜索</el-button>
          <el-button type="warning" :icon="Refresh" :disabled="disabledbtn" @click="resetSearch">重置</el-button>
        </el-space>
      </el-col>
    </el-row>
    <div class="mb10">
      <el-text class="mx-1"> 查询结果：</el-text>
    </div>
    <el-space wrap class="mb20">
      <el-button type="primary" :icon="Plus" :disabled="disabledbtn" @click="changeFormStatus('add')" v-permission="'add'">新增</el-button>
      <el-popconfirm placement="top" width="160" title="你确定要删除吗?" @confirm="batchDelete">
        <template #reference>
          <el-button type="danger" :icon="Delete" :disabled="disabledbtn">批量删除 </el-button>
        </template>
      </el-popconfirm>
      <el-button type="primary" :icon="Download" :disabled="disabledbtn" @click="handleExportRecycleGoodsInfo">导出</el-button>
      <el-button type="primary" :icon="Upload" :disabled="disabledbtn" @click="importDialogVisible = true">导入</el-button>
    </el-space>

    <el-table :data="tableList" border class="table" row-key="id" ref="multipleTableRef" v-loading="loading" :reserve-selection="true" @row-dblclick="rowDblclick">
      <el-table-column type="index" align="center"> </el-table-column>
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="image" label="图片" width="150" align="center">
        <template #default="scope">
          <el-image style="width: 60px; height: 60px" :src="IMG_URL + scope.row.image"> </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="category_name" label="型号" align="center"> </el-table-column>
      <el-table-column prop="name" label="名称" align="center"> </el-table-column>
      <el-table-column prop="price" label="最高估价" align="center"> </el-table-column>
      <el-table-column prop="on_sale" label="上下架状态" align="center">
        <template #default="scope">
          <div class="w-tag">
            <el-tag :type="scope.row.on_sale == 1 ? 'success' : 'danger'">{{ scope.row.on_sale == 1 ? "上架" : "下架" }}</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="sort" label="排序" align="center">
        <template #default="scope">
          <div class="">
            <el-input v-model.trim.number="scope.row.sort" placeholder="请输入内容" @change="handleSort(scope.row)"></el-input>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="create_time" label="创建时间" align="center" :formatter="(row: IRecycledGoodsInfoList) => handleVerifyFormatDate(row.create_time)"> </el-table-column>
      <el-table-column label="操作" width="190" align="center">
        <template #default="scope">
          <div class="control-flex">
            <el-button type="primary" link :icon="View" @click="handleViewEdit(scope.row, 'view', '查看')">查看</el-button>
            <el-button type="primary" link :icon="EditPen" v-permission="'edit'" @click="handleViewEdit(scope.row, 'edit', '编辑')">编辑</el-button>
            <el-button type="success" link :icon="EditPen" :disabled="scope.row.on_sale === '1'" v-permission="'changeOnSale'" @click="handleUpdatetatus(scope.row, '1')">上架 </el-button>
            <el-button type="warning" link :icon="EditPen" :disabled="scope.row.on_sale === '0'" v-permission="'changeOnSale'" @click="handleUpdatetatus(scope.row, '0')">下架 </el-button>
            <div v-permission="'delete'">
              <el-popconfirm placement="top" width="160" title="你确定要删除吗?" @confirm="deleteInfo([scope.row.id])">
                <template #reference>
                  <el-button link :icon="Delete" type="danger">删除</el-button>
                </template>
              </el-popconfirm>
            </div>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        background
        @update:current-page="handleCurrentChange"
        @update:page-size="handleSizeChange"
        layout="total, sizes, prev, pager, next, jumper"
        :page-size="searchCondition.size"
        :current-page="searchCondition.current"
        :page-sizes="[10, 20, 30, 40, 50, 100]"
        :total="total"
        :hide-on-single-page="false">
      </el-pagination>
    </div>
    <UploadDialog v-model:editVisible="importDialogVisible" @handleSuccess="handleSuccess" />
  </div>
</template>

<script setup lang="ts">
import UploadDialog from "@/components/recoveryManage/recycledGoodsInfo/UploadDialog.vue";
import { View, Delete, Download, Upload, EditPen, Search, Plus, Refresh } from "@element-plus/icons-vue";
import type { ISort, ViewMode, ViewModeFilter } from "@/types/common";
import { exportExcel, handleVerifyFormatDate } from "@/utils/utils";
import { useState } from "@/hooks/useState.ts";
import { IMG_URL } from "@/utils/config";
import type { IRecycledGoodsInfoList, ISearchRecycledGoodsInfo } from "@/types/recoveryManage/recycledGoodsInfo";
import { deleteRecycleGoodsInfo, exportRecycleGoodsInfo, getRecycleGoodsInfo, putRecycleGoodsChangeOnSaleInfo, putRecycleGoodsSortInfo } from "@/utils/api/recycleGoods";
import type { IDictData } from "@/types/dict";
import type { IRecycleCategory } from "@/types/recoveryManage/recycleCategory";
import type { IChangeOnSale } from "@/types/recoveryManage/recoveryType";
const { disabledbtn, loading, toggleState } = useState();
interface Props {
  categoryList: Array<IRecycleCategory>;
  whetherStatue: Array<IDictData>;
}
const { categoryList, whetherStatue } = defineProps<Props>();
const emit = defineEmits<{
  handleAdd: [code: ViewMode];
  handleViewEdit: [id: number, code: ViewModeFilter, name: string];
}>();
/* 暴露一个方法给父组件使用 */
defineExpose({
  getTableInfo
});

const multipleTableRef = useTemplateRef("multipleTableRef"); /* 列表组件的引用 */
const total = ref(0);
const importDialogVisible = ref(false);
const searchCondition = reactive<ISearchRecycledGoodsInfo>({
  name: "",
  category_id: "",
  on_sale: "",
  current: 1,
  size: 10
});
const tableList = ref<Array<IRecycledGoodsInfoList>>([]);

onMounted(() => {
  getTableInfo();
});
/* 搜索 */
function searchInfo() {
  searchCondition.current = 1;
  searchCondition.size = 10;
  getTableInfo();
}

/**
 * 重置搜索内容
 */
function resetSearch() {
  searchCondition.name = "";
  searchCondition.category_id = "";
  searchCondition.on_sale = "";
  searchInfo();
}

/**
 * 切换表单状态（ 添加、编辑、查看 ，隐藏none ）
 */
function changeFormStatus(state: ViewMode) {
  // formStatus.value = state;
  emit("handleAdd", state);
}
/* 处理排序 */
function handleSort({ id, sort }: ISort) {
  if (typeof sort !== "number") {
    ElMessage.warning("请输入数字");
    return;
  }
  putRecycleGoodsSortInfo({ id, sort })
    .then(() => {
      ElMessage.success("修改成功");
      getTableInfo();
    })
    .catch(() => {});
}

/* 请求：获取表格中数据 */
function getTableInfo() {
  toggleState(true);
  getRecycleGoodsInfo<IRecycledGoodsInfoList, ISearchRecycledGoodsInfo>(searchCondition)
    .then(res => {
      tableList.value = res.result.data;
      total.value = res.result.total;
    })
    .finally(() => {
      toggleState(false);
    });
}

/* 显示第几页 */
function handleCurrentChange(val: number) {
  searchCondition.current = val;
  getTableInfo();
}

/* 每页显示几条 */
function handleSizeChange(val: number) {
  searchCondition.size = val;
  getTableInfo();
}

/* 触发处理 查看编辑事件 */
function handleViewEdit(row: IRecycledGoodsInfoList, code: ViewModeFilter, name: string) {
  emit("handleViewEdit", row.id, code, name);
}

/* 双击当前行 */
function rowDblclick(row: IRecycledGoodsInfoList) {
  multipleTableRef.value!.toggleRowSelection(row);
}

/* 批量删除 */
function batchDelete() {
  /* 获取选中的数据 */
  let selection = multipleTableRef.value!.store.states.selection.value;
  if (selection.length === 0) {
    ElMessage.warning("请至少选择一条数据");
    return;
  }
  let idArray = [];
  for (const item of selection) {
    idArray.push(item.id);
  }
  deleteInfo(idArray);
}
/* 删除后的信息 */
function deleteInfo(idArray: Array<number>) {
  toggleState(true);
  deleteRecycleGoodsInfo({ idArray })
    .then(() => {
      /* 当删除成功后，删除对应选中的数据或单个数据 */
      tableList.value = tableList.value.filter((item: IRecycledGoodsInfoList) => !idArray.includes(item.id));
      ElMessage.success(`成功删除了${idArray.length}条数据`);
      multipleTableRef.value!.clearSelection();
      total.value = total.value - idArray.length;
    })
    .catch((error: Error) => {
      console.log(error);
    })
    .finally(() => {
      toggleState(false);
    });
}

/* 上下架 */
function handleUpdatetatus(row: IRecycledGoodsInfoList, on_sale: string) {
  updateStatus({ id: row.id, on_sale });
}
/* 更新商品状态 */
function updateStatus(data: IChangeOnSale) {
  toggleState(true);
  putRecycleGoodsChangeOnSaleInfo(data)
    .then(() => {
      const item = tableList.value.find(item => item.id === data.id);
      if (item) {
        item.on_sale = data.on_sale;
        ElMessage.success(`数据修改成功`);
      }
      /* 取消选择 */
      multipleTableRef.value!.clearSelection();
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}
/* 导出文件 */
function handleExportRecycleGoodsInfo() {
  toggleState(true);
  exportRecycleGoodsInfo({
    ...searchCondition,
    time: new Date().getTime()
  })
    .then(res => {
      ElMessage.success("请稍后，正在下载中...");
      exportExcel(res, "回收商品列表" + new Date().getTime());
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}

/* 导入文件成功 */
function handleSuccess() {
  searchInfo();
}
</script>

<style lang="scss" scoped>
/* layout-布局 */
.el-col {
  border-radius: 4px;
}

.mb10 {
  margin-bottom: 10px;
}
/* 关键：列表右侧操作按钮的对其 */
:deep(.el-space__item) {
  line-height: 15px;
}

.el-button.is-text + .el-button.is-text {
  margin-left: 0;
}

.bg-purple-dark {
  background: #99a9bf;
}

.bg-purple {
  background: #d3dce6;
}

.bg-purple-light {
  background: #e5e9f2;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}

.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}

.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.del-dialog-cnt {
  font-size: 16px;
  text-align: center;
}

.table {
  width: 100%;
  font-size: 14px;
}
.textAlignCenter {
  text-align: center;
}

/* 确定按钮的显示与隐藏 */
.displaybtn {
  display: none;
}

/* 提示图标设置 */
.icon-wzg-config {
  height: 30px;
  line-height: 30px;
}

/* 修改Switch开关 */
.el-switch {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}
/* 修改select的盒模型 */
.el-select {
  display: block;
}
</style>
